package com.dushibao.dao;


import com.dushibao.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserMenuDao {

    public void delete(Long userId){
        try{
            String sql = "delete from dushibao_user_menu where user_id = "+userId;
            Connection conn = DBUtils.getConnection();
            conn.prepareStatement(sql).executeUpdate();
            DBUtils.close(conn);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    public void save(Long userId, List<Long> menuIds){
        String sql = "insert into dushibao_user_menu(user_id,menu_id) values(?,?)";

        for (Long menuId:menuIds) {
            try{
                Connection conn = DBUtils.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql);

                stmt.setLong(1,userId);
                stmt.setLong(2,menuId);
                stmt.executeUpdate();
                DBUtils.close(stmt,conn);

            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }

    public List<Long> getUserMenuIds(Long userId) {
        try{
            String sql = "select user_id,menu_id from dushibao_user_menu where user_id = " + userId;
            ResultSet rs  = DBUtils.getConnection().prepareStatement(sql).executeQuery();
            List<Long> menuIds = new ArrayList<>();
            while (rs.next()){
                Long menuId = rs.getLong("menu_id");
                menuIds.add(menuId);
            }

            return menuIds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
